const { useState, useEffect } = React;
const { Modal, Button, Form, Input, Radio, Switch, Checkbox, message, Select, Col, Row } = antd;

const { Option } = Select;

const ProptOption = (props) => {
  const { vars = [], opts = {}, prompt, onTplOk} = props;
  const [form] = Form.useForm();
  const [options, setOptions] = useState({});
  const [prompt_, setPrompt] = useState({});
  const [newOptions, setNewOptions] = useState({});
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    prn(vars, opts, prompt)

    form.setFieldsValue(prompt?.formValues || {});
    setOptions(opts || {});
    // setPrompt(prompt?.content || {})
  }, [prompt, opts]);


  const handleEachMatch = async (matches, data) => {

    prn('matches', matches)
    if (matches) {
      for (let match of matches) {
        match = match.replace(/{{/, '')
        match = match.replace(/}}/, '')
        const match_var = match
        match = match.replace(/prompt_/, '')

        let pt = await db.prompts.get(+match)

        if(pt) {
          data[match_var] = pt.content
        }      
      }
    }

    return data
  }

  const addData = async (data, tpl) => {
    const regex = /\{\{prompt_\d+\}\}/g;
    const matches = tpl.match(regex);

    data = await handleEachMatch(matches, data)
    prn('data',  data)

    return data
  }

  const buildTplWithValues = async ()=>{
      let formValues = await form.validateFields()
      prn('buildTplWithValues formValues', formValues)

      let tpl = prompt.content
      let data = formValues

      data = await addData(data, tpl)
  
      const ret = $.template(tpl, data)


      return ret;
  }


  const buildTpl = async ()=>{
      let ret = await buildTplWithValues()
      onTplOk(ret)
  }

  function handleClick() {
    buildTpl()
  }

  const copyResult = async ()=>{
      let ret = await buildTplWithValues()
      $.copyToClipboard(ret)
  }

  const handleOptionChange = async (fieldName, index, value) => {
    const newItems = [...options[fieldName]];
    newItems[index] = value.trim();
    setOptions(prev => ({ ...prev, [fieldName]: newItems }));
  };


  const handleAddOption = (fieldName) => {
    const value = newOptions[fieldName]?.trim();
    if (!value) return;

    setOptions(prev => ({
      ...prev,
      [fieldName]: [...(prev[fieldName] || []), value]
    }));
    setNewOptions(prev => ({ ...prev, [fieldName]: '' }));
  };


  const renderField = (field) => {
    const { name, type } = field;
    const fieldOptions = options[name] || [];
    const inputStyle = { width: 160, marginRight: 8 };

    const renderOptionsEditor = () => (<div />);

    const _renderOptionsEditor = () => (
      <Space direction="vertical" style={{ width: '100%' }}>
        {fieldOptions.map((opt, index) => (
          <Input
            key={index}
            value={opt}
            style={inputStyle}
            onChange={(e) => handleOptionChange(name, index, e.target.value)}
            placeholder="编辑选项"
          />
        ))}
        <Space>
          <Input
            style={inputStyle}
            value={newOptions[name] || ''}
            onChange={(e) => setNewOptions(prev => ({
              ...prev,
              [name]: e.target.value
            }))}
            placeholder="输入新选项"
          />
          <Button onClick={() => handleAddOption(name)}>添加</Button>
        </Space>
      </Space>
    );

    switch (type) {
      case 'input':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Input />
          </Form.Item>
        );

      case 'switch':
        return (
          <Form.Item
            key={name}
            name={name}
            label={name}
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>
        );

      case 'radio':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Radio.Group>
              <Space direction="vertical">
                {fieldOptions.map((opt, index) => (
                  <Radio key={index} value={opt}>
                    {opt}
                  </Radio>
                ))}
                {renderOptionsEditor()}
              </Space>
            </Radio.Group>
          </Form.Item>
        );

      case 'checkbox':
        return (
          <Form.Item key={name} name={name} label={name}>
            <Checkbox.Group>
              <Space direction="vertical">
                {fieldOptions.map((opt, index) => (
                  <Checkbox key={index} value={opt}>
                    {opt}
                  </Checkbox>
                ))}
                {renderOptionsEditor()}
              </Space>
            </Checkbox.Group>
          </Form.Item>
        );

      default:
        return null;
    }
  };

  return (
    <div>
        <Form form={form} layout="vertical" initialValues={prompt?.formValues}>
          {vars.map(field => renderField(field))}
        </Form>  

         <Button type='link' onClick={copyResult}> copy </Button>
         <Button onClick={handleClick}> ==></Button>
    </div>
  );
};